const fs = require('fs');
const path = require("path");
const inquirer = require('inquirer');
const ejs = require('ejs');
const chalk = require("chalk");
var UUID = require('uuid');
const inq_env = require(path.join(__dirname,'./../template/envserver.js'));
const inq_proj = require(path.join(__dirname,'./../template/project.js'));

/**ejs模板文件 */
var ejs_env = "./../template/envserver.ejs";
var ejs_proj = "./../template/project.ejs";
/**环境配置文件生成路径 */
var save_env = "env.conf.js";
/**项目描述配置文件生成路径 */
var save_proj = "project.conf.js";
/**package.json 路径 */
var savejson = "package.json";
/**pack 和 output 文件夹 */
var pack = "pack";
var output = "dist";
var env = "env";
/**插件在开发环境下的路径 */
var plugpath = "env/hotdog/server/plugins"

/**
 * 生成环境配置文件
 */
function makeEnvConfig() {
   writeConfig(inq_env,ejs_env,save_env);
}

/**
 * 生成项目配置文件
 */
function makeProjectConfig() {
    return new Promise((resolve,reject)=>{
        try{
            writeConfig(inq_proj,ejs_proj,save_proj);
            resolve();
        }catch(err){
            reject(err);
        }
    })
}

/**
 * 生成项目配置文件和修改package.json
 */
function mkProjectConfigAndUpdatePackageJson(){
    var updatePackageJsonPrompt = new Promise(async function(resolve, reject){
        await updatePackageJson().catch(err=>{
            console.log(chalk.red("修改package.json文件失败，请检查文件是否存在"));
            console.log(err);
        });
        // resolve("开始生成项目配置文件...");
        await makeProjectConfig().catch(err=>{
            console.log(chalk.red("生成project.conf.js文件失败"));
            console.log(err);
        });
    });
}

/**
 * 生成配置文件
 */
async function writeConfig(serverconf,ejspath,savepath) {
    //界面输入
    let answerobj = await inquirer.prompt(serverconf)
    answerobj["uuid"] = UUID.v1();
    //获取ejs模板
    let readpath = path.join(__dirname, ejspath)
    let ejsstr = await fs.readFileSync(readpath, 'utf-8');
    //模板数据转换为界面输入数据
    let ret = ejs.render(ejsstr, {
        answerobj: answerobj
      });
    //生成文件输出
    let realpath = path.resolve("./",savepath)
     fs.writeFile(realpath, ret,  function(err) {
        if (err) {
            console.log(chalk.red("[hotdog_cli ERROR]写入配置文件失败"));
            return console.error(err);
        }
        console.log(chalk.yellow("配置文件创建成功！"));
     });
}

/**
 * 修改npm项目配置文件(package.json)
 */
function  updatePackageJson() {
    return new Promise(async function (resolve,reject){
        try{
            /**下载环境命令 */
            let downenv = "node downenv"
            /**打包命令 */
            let build = "webpack-dev-server --open Chrome.exe"
            /**启动Express 环境 */
            let startexpress = "cd express && node app"

            let package={};
            let jsonpath = path.resolve("./",savejson)
            /**读取json文件 */
            try{
                package = readJson(jsonpath);
            }catch(err){
                console.log(chalk.red("[hotdog_cli ERROR]读取"+jsonpath+"文件报错，请检查是否存在"));
                console.log(err);
                return;
            }

            /**添加命令 */
            package["scripts"]["downenv"]=downenv;
            // package["scripts"]["build"]=build;
            package["scripts"]["startexpress"]=startexpress;
            
            /**格式化json */
            let jsonstr = JSON.stringify(package,null,"\t");

            /**写入文件 */
            // await fs.writeFileSync(jsonpath,  jsonstr,  'utf-8'); 
            // console.log(chalk.yellow("package.json文件修改完成"))

            //新建pack和output文件夹
            let packpath = path.resolve("./",pack)
            let outputpath = path.resolve("./",output)
            let envpath = path.resolve("./",env)
            if(!(await fs.existsSync(packpath))){
                await fs.mkdirSync(packpath);
                console.log(chalk.yellow("创建pack文件夹用于打包项目完成"));
            }
            if(!(await fs.existsSync(outputpath))){
                await fs.mkdirSync(outputpath);
                console.log(chalk.yellow("创建disk编译路径完成"));
            }
            if(!(await fs.existsSync(envpath))){
                await fs.mkdirSync(envpath);
                console.log(chalk.yellow("创建env平台环境路径完成"));
            }
            resolve();
        }catch(err){
            reject(err);
        }
    });
}

/**
 * 将json文件读取入对象
 */
 function readJson(confpath) {
    let data = fs.readFileSync(confpath, 'utf-8')
    return JSON.parse(data.toString());
}


exports.updatePackageJson = updatePackageJson;
exports.makeEnvConfig = makeEnvConfig;
exports.makeProjectConfig = makeProjectConfig;
exports.mkProjectConfigAndUpdatePackageJson = mkProjectConfigAndUpdatePackageJson;